package com.seestech.sell.web;

import com.google.code.kaptcha.Constants;
import com.seestech.sell.common.utils.EncodeMD5;
import com.seestech.sell.common.utils.ResponseUtils;
import com.seestech.sell.common.config.ApplicationConfig;
import com.seestech.sell.domain.model.Log;
import com.seestech.sell.domain.model.Menu;
import com.seestech.sell.domain.model.User;
import com.seestech.sell.service.ILogService;
import com.seestech.sell.service.IMenuService;
import com.seestech.sell.service.IUserService;
import com.seestech.sell.service.KaptchaService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


/**
 * Created by idiot on 2017/6/15.
 */
@Controller
public class IndexController extends SuperController {
    private static Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Resource
    private IUserService userService;
    @Resource
    private ILogService logService;
    @Resource
    private IMenuService menuService;
    @Resource
    private KaptchaService kaptchaService;
    @Resource
    private ApplicationConfig applicationConfig;

    @RequestMapping(value = {"/"},method = RequestMethod.GET)
    public String root(){
        //获取用户  如果有"记住我"  使用免密登录
        Subject subject = SecurityUtils.getSubject();
        if(subject.isRemembered()){
            logger.info("======>【记住我】自动登录中.....");
            String username = subject.getPrincipal().toString();
            User user = userService.getUserByName(username);
            baseLogin(user);

            //如果登录成功  跳转到首页
            if(subject.isAuthenticated()){
                //权限验证通过   把当前用户添加到session 并且返回首页
                session_local.get().setAttribute(com.seestech.sell.common.utils.Constants.Regular.onlineUser, userService.getUserByName(username));
                logger.info("【自动登录】成功...进入首页...");
                return "redirect:index.html";
            }
        }
        return "redirect:login.html";
    }

    public void baseLogin(User user) {
        try {
            Subject subject= SecurityUtils.getSubject();
            if (subject.isAuthenticated()) {
                return;
            }

            boolean rememberMe = true;
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getUserPassword(), rememberMe);
            subject.login(token); // 登录

        } catch (Exception e) {
            //做一些异常处理
            logger.error("登录失败......");
        }finally{
            //其他。。
        }
    }

    @RequestMapping(value = {"login"},method = RequestMethod.GET)
    public String toLogin(){
        return "login";
    }

    @ResponseBody
    @RequestMapping(value = "loginIn")
    public String login(User info, String captcha, Model model,
                        @RequestParam(value = "rememberMe", defaultValue = "false") Boolean rememberMe){
        // ResponseInfo<String> responseInfo = new ResponseInfo<>();
        logger.info("开始==》【登录】");
        logger.info("开始判断数据是否为空...");
        //用户信息非空判断  为空返回登录页面
        if(null == info || StringUtils.isEmpty(info.getUserName()) || StringUtils.isEmpty(info.getUserPassword()) || StringUtils.isEmpty(captcha)){
            return ResponseUtils.responseError("用户名、密码、验证码不能为空...");
        }
        logger.info("开始判断验证码是否正确...");
        //判断验证码  错误返回登录页面
        //从session中取出验证码text值
        String expected = (String) session_local.get().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        logger.info("验证码==========>" + expected);
        if(!captcha.equalsIgnoreCase(expected)){
            logger.error("验证码错误...");
            return ResponseUtils.responseError("验证码有误...");
        }
        logger.info("开始shiro权限验证...");
        //shiro验证
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(info.getUserName(), EncodeMD5.GetMD5Code(info.getUserPassword()), rememberMe);
            subject.login(token);
            if(subject.isAuthenticated()){
                //权限验证通过   把当前用户添加到session 并且返回首页
                session_local.get().setAttribute(com.seestech.sell.common.utils.Constants.Regular.onlineUser, userService.getUserByName(info.getUserName()));
                // logger.info("sessionId===>" + request.getRequestedSessionId());
                //写入数据库登录日志
                Log log = new Log();
                log.setLogMessage("管理员用户登录");        //设置日志信息
                log.setRequestUrl(request_local.get().getRequestURI().toString());  //设置请求路径
                log.setUserId(getUser().getUserId());                        //设置userId
                log.setCreateUser(getUser().getUserId());
                logService.addloginLog(log);
                logger.info("登录验证成功...进入首页...");
                return ResponseUtils.responseSuccess("登录成功...");
            }
        } catch (AuthenticationException e) {
            logger.error("登录验证失败...错误原因："+e.getMessage());
            logger.error(e.getMessage(), e);
        }
        logger.info("返回登录页面...");
        return ResponseUtils.responseError("密码错误或者用户名不存在,请重试...");
    }

    /**
     * @author idiot
     * @description 跳转首页
     * @return
     */
    @RequestMapping(value = {"index.html"})
    public String indexPage(Model model){
        logger.info("加载首页资源...");
        //获取用户信息  从session里面
        User user = getUser();
        if(user == null){
            logger.info("用户信息有误...");
            request_local.get().setAttribute("error", "该用户不存在,请重试...");
            return "redirect:login.html";
        }
        //从数据库中查询menu  一级菜单
        List<Menu> menus = menuService.getFirstLevelMenusByUserId(user.getUserId());
        //加载二级菜单信息
        for(Menu menu : menus){
            // List<Menu> menuItems = menuService.getMenusByParentId(menu.getMenuId());
            List<Menu> menuItems = menuService.getMenusByParentIdAndUserId(menu.getMenuId(), user.getUserId());
            menu.setListMenus(menuItems);
        }
        model.addAttribute("version", applicationConfig.getVersion());
        model.addAttribute("menus", menus);
        model.addAttribute(com.seestech.sell.common.utils.Constants.Regular.onlineUser,getUser());
        return "index";
    }

    /**
     * @dscription 欢迎页面
     * @return
     */
    @RequestMapping(value = "welcome", method = RequestMethod.GET)
    public String welcome(){
        return "welcome";
    }

    /**
     * @description 退出时加载登录页
     * @return
     */
    @RequestMapping(value = "loginOut", method = RequestMethod.GET)
    public String loginOut(){
        request_local.get().getSession().setAttribute(com.seestech.sell.common.utils.Constants.Regular.onlineUser, null);
        //获取用户
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:login.html";
    }

    /**
     * @author idiot
     * @description  生成验证码
     * @throws Exception
     */
    @RequestMapping(value = "captcha-image")
    public void getKaptchaImage() throws Exception {
        //输出验证码   同时保存结果到session
        kaptchaService.createImage(response_local.get(), session_local.get(), Constants.KAPTCHA_SESSION_KEY);
        // logger.info("sessionId===>" + request.getRequestedSessionId());
    }

    /**
     * @description 上传头像
     * @param key  表单中文件的name属性
     * @return
     */
    @PostMapping(value = "uploadImage")
    @ResponseBody
    public Object uploadImage(String key){
        logger.info("开始上传头像......");
        String result = uploadImage(applicationConfig, com.seestech.sell.common.utils.Constants.Regular.my_head_image, key);
        if(result != null && !"".equals(result))
            return ResponseUtils.responseSuccess(result);
        else
            return ResponseUtils.responseError("上传失败");
    }


    //前往导航页
    @RequestMapping(value = "nav.html", method = RequestMethod.GET)
    public String nav(){
        logger.info("前往导航页面========>>>>>>>");
        return "nav";
    }

}